import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import type { Note } from '@/services/disk'
import {
  getNoteList,
  getNoteDetail,
  saveNote,
  deleteNote,
  shareNote,
  unshareNote,
} from '@/services/disk'

// 定义笔记状态类型
interface NoteState {
  noteList: Note[]
  currentNote: Note | null
  loading: boolean
  error: string | null
  pagination: {
    currentPage: number
    pageSize: number
    total: number
  }
  searchParams: {
    keyword: string
  }
}

export const useNoteStore = defineStore('note', () => {
  // 状态定义
  const noteList = ref<Note[]>([])
  const currentNote = ref<Note | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
  })

  const searchParams = reactive({
    keyword: '',
  })

  // 获取笔记列表
  async function fetchNoteList(params = {}) {
    loading.value = true
    error.value = null

    try {
      // 合并分页参数和搜索参数
      const queryParams = {
        page: pagination.currentPage,
        limit: pagination.pageSize,
        keyword: searchParams.keyword,
        ...params,
      }

      const response = await getNoteList(queryParams)

      if (response.code === 0) {
        noteList.value = response.data.list || []
        pagination.total = response.data.total || 0
        pagination.currentPage = response.data.page || 1
        pagination.pageSize = response.data.limit || 10
      } else {
        error.value = response.msg || '获取笔记列表失败'
      }
    } catch (err: any) {
      error.value = err.message || '获取笔记列表时发生错误'
    } finally {
      loading.value = false
    }
  }

  // 获取笔记详情
  async function fetchNoteDetail(id: number) {
    loading.value = true
    error.value = null

    try {
      const response = await getNoteDetail(id)

      if (response.code === 0) {
        currentNote.value = response.data
      } else {
        error.value = response.msg || '获取笔记详情失败'
        currentNote.value = null
      }
    } catch (err: any) {
      error.value = err.message || '获取笔记详情时发生错误'
      currentNote.value = null
    } finally {
      loading.value = false
    }
  }

  // 保存笔记（新建或更新）
  async function saveNoteData(noteData: Partial<Note>) {
    loading.value = true
    error.value = null

    try {
      const response = await saveNote({
        id: noteData.id,
        name: noteData.name || noteData.title || '',
        content: noteData.content || '',
        file_ids: noteData.file_ids,
      })

      if (response.code === 0) {
        // 保存成功后更新当前笔记
        currentNote.value = response.data
        return true
      } else {
        error.value = response.msg || '保存笔记失败'
        return false
      }
    } catch (err: any) {
      error.value = err.message || '保存笔记时发生错误'
      return false
    } finally {
      loading.value = false
    }
  }

  // 删除笔记
  async function removeNote(id: number) {
    loading.value = true
    error.value = null

    try {
      const response = await deleteNote(id)

      if (response.code === 0) {
        // 删除成功后从列表中移除
        noteList.value = noteList.value.filter((note: Note) => note.id !== id)
        pagination.total -= 1
        return true
      } else {
        error.value = response.msg || '删除笔记失败'
        return false
      }
    } catch (err: any) {
      error.value = err.message || '删除笔记时发生错误'
      return false
    } finally {
      loading.value = false
    }
  }

  // 分享笔记
  async function shareNoteData(noteId: number, userIds?: string, departmentIds?: string) {
    loading.value = true
    error.value = null

    try {
      const response = await shareNote({
        id: noteId,
        user_ids: userIds,
        department_ids: departmentIds,
      })

      if (response.code === 0) {
        // 分享成功后刷新当前笔记
        if (currentNote.value && currentNote.value.id === noteId) {
          await fetchNoteDetail(noteId)
        }
        return true
      } else {
        error.value = response.msg || '分享笔记失败'
        return false
      }
    } catch (err: any) {
      error.value = err.message || '分享笔记时发生错误'
      return false
    } finally {
      loading.value = false
    }
  }

  // 取消分享笔记
  async function unshareNoteData(noteId: number) {
    loading.value = true
    error.value = null

    try {
      const response = await unshareNote(noteId.toString())

      if (response.code === 0) {
        // 取消分享成功后刷新当前笔记
        if (currentNote.value && currentNote.value.id === noteId) {
          await fetchNoteDetail(noteId)
        }
        return true
      } else {
        error.value = response.msg || '取消分享笔记失败'
        return false
      }
    } catch (err: any) {
      error.value = err.message || '取消分享笔记时发生错误'
      return false
    } finally {
      loading.value = false
    }
  }

  // 重置搜索参数
  function resetSearch() {
    searchParams.keyword = ''
    pagination.currentPage = 1
  }

  // 重置状态
  function resetState() {
    noteList.value = []
    currentNote.value = null
    loading.value = false
    error.value = null
    pagination.currentPage = 1
    pagination.pageSize = 10
    pagination.total = 0
    searchParams.keyword = ''
  }

  // 返回状态和方法
  return {
    // 状态
    noteList,
    currentNote,
    loading,
    error,
    pagination,
    searchParams,

    // 方法
    fetchNoteList,
    fetchNoteDetail,
    saveNoteData,
    removeNote,
    shareNoteData,
    unshareNoteData,
    resetSearch,
    resetState,
  }
})
